﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using RenRen.Session;
using System.Web.Configuration;

namespace RenRen.Web.Mvc {
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class RenRenAuthorizationAttribute : ActionFilterAttribute {
        public bool IsXnml { get; set; }

        /// <summary> 
        /// The APi key for this application given by renren
        /// </summary>
        public string ApiKey { get; set; }

        /// <summary> 
        /// The APi Secret for this application given by renren
        /// </summary>
        public string Secret { get; set; }

        public override void OnActionExecuting(ActionExecutingContext c) {
            CanvasSession session = null;
            if (IsXnml) {
                session = new XnmlCanvasSession(ApiKey ?? WebConfigurationManager.AppSettings["ApiKey"], Secret ?? WebConfigurationManager.AppSettings["Secret"]);
            } else {
                session = new IFrameCanvasSession(ApiKey ?? WebConfigurationManager.AppSettings["ApiKey"], Secret ?? WebConfigurationManager.AppSettings["Secret"]);
            }

            if (string.IsNullOrEmpty(session.SessionKey)) {
                c.Result = new ContentResult { Content = session.GetRedirect() };
            }
        }
        public override void OnResultExecuted(ResultExecutedContext c) {
            base.OnResultExecuted(c);
            if (!IsXnml) {
                c.HttpContext.Response.AppendHeader("P3P", "CP=\"CAO PSA OUR\"");
            }

        }

    }
}